import shutil
import config
import requests

from loguru import logger
from mutils.zip import unzip_dir
import sys
import os

import requirements

logger.add(
    sink="./logs/{time:YYYY-MM-DD}.log",
    # format = "{time:HH:mm:ss} {level} {message}",
    level="INFO",
    rotation="00:00",
)


def get_laetst_module():
    url = config.host + config.laetst_url

    params = {"module_name": config.module_name}

    r = requests.get(url, params=params)

    if r.status_code != 200:
        logger.error(f"get laetst module failed: {r.status_code}")
        return None

    rspJson = r.json()

    if rspJson["code"] != 0:
        logger.error(f"get laetst module failed: {rspJson}")
        return None

    return rspJson["data"]


def download_zip(url, path):
    r = requests.get(url, stream=True)
    if r.status_code != 200:
        logger.error(f"download zip failed: {r.status_code}")
        return False

    # 目录不存在先创建
    dir = os.path.dirname(path)
    if not os.path.exists(dir):
        os.makedirs(dir)

    with open(path, "wb") as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)

    return True


def source_path(relative_path):
    # 是否Bundle Resource
    if getattr(sys, "frozen", False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


def run():
    # 先删除./modules目录
    module_path = source_path(f"./modules/")
    if os.path.exists(source_path("./modules")):
        shutil.rmtree(module_path)

    logger.info("fetch laetst module")
    module = get_laetst_module()
    logger.success(f"get laetst module success: {module}")

    if module is None:
        logger.error("get laetst module failed")
        raise Exception("get laetst module failed")

    module_zip_path = source_path(f"./temp/{module['name']}-{module['version']}.zip")

    logger.info(f"download zip: {module['zip_url']}")
    if not download_zip(config.host + module["zip_url"], module_zip_path):
        raise Exception("download zip failed")

    logger.info(f"unzip zip: {module_zip_path}")
    unzip_dir(module_zip_path, module_path)

    sys.path.append(module_path)
    os.chdir(module_path)

    logger.info(f"launch_code: {module['launch_code']}")
    exec(module["launch_code"])


if __name__ == "__main__":
    try:
        run()
    except Exception as e:
        logger.exception(e)
